package com.example.demo.http.controllers.admin;

import com.example.demo.models.admin.Admin;
import com.example.demo.services.LoginService;
import com.example.demo.services.system.JWTService;
import com.example.demo.services.system.ResultService;
import gaarason.database.contract.eloquent.Record;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/admin/")
public class LoginController {
    @Resource
    Admin.Model adminModel;

    //登录
    @GetMapping("/login")
    ResultService.Result login(@RequestParam Map<String, String> params) {
        //返回值
        ResultService.Result result = ResultService.getNormalResult();

        String number = params.get("number");
        String password = params.get("password");
        if (Objects.isNull(number) || Objects.isNull(password)) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "请输入用户名和密码";
            return result;
        } else {
            if (LoginService.check(number, password)) {
                //用户名和密码正确，查询到本地的用户，并生成JWT
                Record<Admin, Long> record = adminModel.newQuery().where("number", number).first();
                if (record != null) {
                    //生成token
                    String token = JWTService.generateToken(record.getEntity());
                    Map<String, String> data = new HashMap<>();
                    data.put("token", token);
                    data.put("number", number);
                    data.put("name", record.getEntity().getName());
                    result.data = data;
                    return result;
                } else {
                    result.code = ResultService.CLIENT_ERROR;
                    result.msg = "用户名或密码错误";
                    return result;
                }
            } else {
                result.code = ResultService.CLIENT_ERROR;
                result.msg = "用户名或密码错误";
                return result;
            }
        }
    }
}
